package cn.sansi.plugin;

import cn.sansi.common.exception.BizException;
import cn.sansi.plugin.constant.PluginErrorCode;
import cn.sansi.plugin.container.ClassLoaderSwapper;
import cn.sansi.plugin.container.JarLoader;
import cn.sansi.plugin.container.LoadUtil;

import java.util.Map;

/**
 * @author 林芳崽
 * @date 2024/3/11
 */
public class Engine {

    private static final ThreadLocal<ClassLoaderSwapper> context = ThreadLocal.withInitial(ClassLoaderSwapper::newCurrentThreadClassLoaderSwapper);

    public static void callTask(String pluginName,String configValue, Map<String, Object> args) {
        AbstractPlugin plugin = LoadUtil.loadPlugin(pluginName,configValue);
        if (plugin instanceof AbstractTaskPlugin) {
            ClassLoaderSwapper classLoaderSwapper = context.get();
            JarLoader jarLoader= LoadUtil.getJarLoader(pluginName);
            try {
                classLoaderSwapper.setCurrentThreadClassLoader(jarLoader);
                ((AbstractTaskPlugin) plugin).call(args);
            }finally {
                classLoaderSwapper.restoreCurrentThreadClassLoader();
            }
        } else {
            throw BizException.asBizException(PluginErrorCode.INSTALL_ERROR, "插件类型无效");
        }
    }

    public static Map<String, Object> callService(String pluginName,String configValue, Map<String, Object> args) {
        AbstractPlugin plugin = LoadUtil.loadPlugin(pluginName,configValue);
        if (plugin instanceof AbstractServicePlugin) {
            ClassLoaderSwapper classLoaderSwapper = context.get();
            JarLoader jarLoader= LoadUtil.getJarLoader(pluginName);
            try {
                classLoaderSwapper.setCurrentThreadClassLoader(jarLoader);
                return ((AbstractServicePlugin) plugin).call(args);
            }finally {
                classLoaderSwapper.restoreCurrentThreadClassLoader();
            }
        } else {
            throw BizException.asBizException(PluginErrorCode.INSTALL_ERROR, "插件类型无效");
        }
    }
}
